package com.attilax.auto.web;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;

public class WebDriverUtil {
	
	
	public static WebDriverUtil newx()
	{
		return new WebDriverUtil();
	}

	public   boolean isDisconn(FirefoxDriver driver) {
		try {
			System.out.println(driver.getCurrentUrl());
		} catch (UnreachableBrowserException e) {
			return true;
		}catch(WebDriverException e)
		{
			return true;
		}
		
		return false;
	}
	
	public void closeAlert(FirefoxDriver driver) {
		try {
			
		//JavaScriptExecutor js = (JavaScriptExecutor)driver;
			// Override window.alert to store the prompt and accept it automatically
		 // j
		String js="window.alert = function(msg) { document.bAlert = true; document.lastAlert=msg; }";
		driver.executeScript(js, driver.findElement(By.tagName("body")));
		//	js.ExecuteScript();
			Alert alert = driver.switchTo().alert();
			// Get the text from the alert

			String alertText = alert.getText();
			// Accept the alert
			alert.accept();
			try {
				alert.dismiss();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		} catch (NoAlertPresentException e) {
			 System.out.println("There is no alert appear!");  

		}catch(UnreachableBrowserException e)
		{
			//renewBrowser(blogName.get());
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public   FirefoxDriver getDriverInstan(FirefoxDriver driver) {
		try {
			// driver=(FirefoxDriver)
			// propMap.get(blogMap.get("pubber").toString()+"_driver");
			if (driver != null)
				if (isDisconn(driver))
					driver = null;
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (driver == null) {
			driver = new FirefoxDriver();
			// propMap.put(blogMap+"_driver",driver);
		}
		return driver;
	}

}
